<?php

namespace app\admin\model\yiliao;

use think\Model;


class Promotion extends Model
{

    

    

    // 表名
    protected $name = 'yiliao_promotion';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'integer';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = false;

    // 追加属性
    protected $append = [
        'homedata_text',
        'status_text'
    ];

    protected static function init()
    {
        self::beforeUpdate(function ($row) {
            $start_time = '';
            $end_time = '';
            if(!empty($row['start'])){
                $pk = $row->getPk();
                $start_time = strtotime($row['start']);
            }
            if(!empty($row['end'])){
                $pk = $row->getPk();
                $end_time = strtotime($row['end']);
            }
            $row->getQuery()->where($pk, $row[$pk])->update(['start_time' => $start_time,'end_time'=>$end_time]);
        });
        self::afterInsert(function ($row) {
            $start_time = '';
            $end_time = '';
            if(!empty($row['start'])){
                $pk = $row->getPk();
                $start_time = strtotime($row['start']);
            }
            if(!empty($row['end'])){
                $pk = $row->getPk();
                $end_time = strtotime($row['end']);
            }
            $row->getQuery()->where($pk, $row[$pk])->update(['start_time' => $start_time,'end_time'=>$end_time]);
        });
    }
    
    public function getHomedataList()
    {
        return ['1' => __('Homedata 1'), '0' => __('Homedata 0')];
    }

    public function getStatusList()
    {
        return ['normal' => __('Normal'), 'hidden' => __('Hidden')];
    }


    public function getHomedataTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['homedata']) ? $data['homedata'] : '');
        $list = $this->getHomedataList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function getStatusTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['status']) ? $data['status'] : '');
        $list = $this->getStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }

    public function pro()
    {
        return $this->belongsTo('Pro', 'yiliao_pro_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }
}
